const path = require('path')
const {PROJECT_PATH, isDev} = require('../constant.js')
const HtmlWebpackPlugin = require('html-webpack-plugin')

const PLUGINS = [
	new HtmlWebpackPlugin({
		template: path.resolve(PROJECT_PATH, './public/index.html'),
		filename: 'index.html',
		// inject: true,
		cache: false,
		minify: isDev
			? false
			: {
					removeAttributeQuotes: true,
					collapseWhitespace: true,
					removeComments: true,
					collapseBooleanAttributes: true,
					collapseInlineTagWhitespace: true,
					removeRedundantAttributes: true,
					removeScriptTypeAttributes: true,
					removeStyleLinkTypeAttributes: true,
					minifyCSS: true,
					minifyJS: true,
					minifyURLs: true,
					useShortDoctype: true
				}
	})
]

const getCssLoaders = (importLoaders) => [
	'style-loader',
	{
		loader: 'css-loader',
		options: {
			modules: true,
			sourceMap: isDev,
			importLoaders // 在被 css-loader 处理前，还需要处理的 loader 数量
		}
	},
	'postcss-loader'
]

module.exports = {
	// 设置环境模式
	mode: isDev ? 'development' : 'production',
	entry: {
		app: path.resolve(PROJECT_PATH, './src/index.tsx')
	},
	output: {
		filename: `js/[name]${isDev ? '' : '.[hash:8]'}.js`,
		path: path.resolve(PROJECT_PATH, './dist')
	},
	plugins: PLUGINS,
	resolve: {
		extensions: ['.tsx', '.ts', '.js', '.json'],
		alias: {
			'@': path.resolve(PROJECT_PATH, './src'),
			'@components': path.resolve(PROJECT_PATH, './src/components')
		}
	},
	module: {
		rules: [
			{
				test: /\.css$/,
				use: [...getCssLoaders(1)]
			},
			{
				test: /\.less$/,
				use: [...getCssLoaders(2), 'less-loader']
			},
			// 处理图片、文件、字体
			{
				test: /\.(png|svg|jpg|jpeg|gif)$/i,
				type: 'asset/resource'
			},
			{
				test: /\.(woff|woff2|eot|ttf|otf)$/i,
				type: 'asset/resource'
			},
			{
				test: /\.txt/,
				type: 'asset/source'
			},
			{
				// 通用文件则使用 asset，此时会按照默认条件自动决定是否转换为 Data URI
				test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
				type: 'asset',
				parser: {
					// 如果文件大小小于 8kb，那么会转换为 data URI，否则为单独文件。
					// 8kb 是默认值，你可以根据需要进行调整
					dataUrlCondition: {
						maxSize: 8 * 1024 // 8kb
					}
				}
			},
			//  react babel
			{
				test: /\.(tsx?|js)$/,
				loader: 'babel-loader',
				options: {cacheDirectory: true},
				exclude: /node_modules/
			}
		]
	}
}
